package dao;

import pojo.User;
import utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserDAO {

    // 注册新用户
    public void register(User user) throws SQLException {
        String sql = "INSERT INTO tb_users (is_active,fullname, username, password,avatar, role_type, email, phone_number, address, bio) " +
                     "VALUES (?,?, ?, ?, ?,?, ?, ?, ?, ?)";
        JDBCUtils.execute(sql,
                user.getIsActive(),
                user.getFullname(),
                user.getUsername(),
                user.getPassword(),
                user.getAvatar(),
                user.getRoleType(),
                user.getEmail(),
                user.getPhoneNumber(),
                user.getAddress(),
                user.getBio());
    }

    // 根据用户名查询用户
    public User findByUsername(String username) throws SQLException {
        String sql = "SELECT * FROM tb_users WHERE username = ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, username);
        if (rs.next()) {
            return mapResultSetToUser(rs);
        }
        return null;
    }

    // 用户登录验证
    public User login(String username, String password) throws SQLException {
        String sql = "SELECT * FROM tb_users WHERE username = ? AND password = ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, username, password);
        if (rs.next()) {
            return mapResultSetToUser(rs);
        }
        return null;
    }

    // 查询所有用户
    public List<User> findAllUsers() throws SQLException {
        String sql = "SELECT * FROM tb_users";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql);
        List<User> userList = new ArrayList<>();
        while (rs.next()) {
            userList.add(mapResultSetToUser(rs));
        }
        return userList;
    }

    // 分页模糊查询用户并统计总数
    public Map<String, Object> findUsersByPageAndName(String keyword, int pageNum, int pageSize) throws SQLException {
        int offset = (pageNum - 1) * pageSize;
        String sqlQuery = "SELECT * FROM tb_users WHERE fullname LIKE ? LIMIT ?, ?";
        String sqlCount = "SELECT COUNT(*) FROM tb_users WHERE fullname LIKE ?";

        // 查询符合条件的用户列表
        ResultSet rsQuery = (ResultSet) JDBCUtils.execute(sqlQuery, "%" + keyword + "%", offset, pageSize);
        List<User> userList = new ArrayList<>();
        while (rsQuery.next()) {
            userList.add(mapResultSetToUser(rsQuery));
        }

        // 查询符合条件的用户总数
        ResultSet rsCount = (ResultSet) JDBCUtils.execute(sqlCount, "%" + keyword + "%");
        int totalRecords = 0;
        if (rsCount.next()) {
            totalRecords = rsCount.getInt(1);
        }

        // 将数据和总记录数封装到Map中
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("data", userList);
        resultMap.put("total", totalRecords);

        return resultMap;
    }

    // 修改密码
    public void updatePassword(String username, String newPassword) throws SQLException {
        String sql = "UPDATE tb_users SET password = ? WHERE username = ?";
        JDBCUtils.execute(sql, newPassword, username);
    }

    // 更新用户信息
    public void updateUser(User user) throws SQLException {
        StringBuilder sqlBuilder = new StringBuilder("UPDATE tb_users SET ");
        List<Object> params = new ArrayList<>();

        if (user.getFullname() != null) {
            sqlBuilder.append("fullname = ?, ");
            params.add(user.getFullname());
        }
        if (user.getRoleType() != null) {
            sqlBuilder.append("role_type = ?, ");
            params.add(user.getRoleType());
        }
        if (user.getEmail() != null) {
            sqlBuilder.append("email = ?, ");
            params.add(user.getEmail());
        }
        if (user.getPhoneNumber() != null) {
            sqlBuilder.append("phone_number = ?, ");
            params.add(user.getPhoneNumber());
        }
        if (user.getAddress() != null) {
            sqlBuilder.append("address = ?, ");
            params.add(user.getAddress());
        }
        if (user.getBio() != null) {
            sqlBuilder.append("bio = ?, ");
            params.add(user.getBio());
        }
        if (user.getAvatar() != null) {
            sqlBuilder.append("avatar = ?, ");
            params.add(user.getAvatar());
        }
        if (user.getLastLogin() != null) {
            sqlBuilder.append("last_login = ?, ");
            params.add(user.getLastLogin());
        }
        if (user.getIsActive() != null) {
            sqlBuilder.append("is_active = ?, ");
            params.add(user.getIsActive());
        }

        // Check if no fields were added
        if (params.isEmpty()) {
            throw new IllegalArgumentException("No fields to update");
        }

        // Remove the trailing comma and space
        sqlBuilder.setLength(sqlBuilder.length() - 2);

        // Add WHERE clause
        sqlBuilder.append(" WHERE id = ?");

        // Add ID parameter
        params.add(user.getId());

        // Execute the dynamic SQL
        JDBCUtils.execute(sqlBuilder.toString(), params.toArray());
    }



    // 删除用户
    public void deleteUser(Long userId) throws SQLException {
        String sql = "DELETE FROM tb_users WHERE id = ?";
        JDBCUtils.execute(sql, userId);
    }

    // 辅助方法：将 ResultSet 映射为 User 对象
    private User mapResultSetToUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getLong("id"));
        user.setFullname(rs.getString("fullname"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setAvatar(rs.getString("avatar"));
        user.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
        user.setRoleType(rs.getString("role_type"));
        user.setEmail(rs.getString("email"));
        user.setPhoneNumber(rs.getString("phone_number"));
        user.setAddress(rs.getString("address"));
        user.setBio(rs.getString("bio"));
        user.setLastLogin(rs.getTimestamp("last_login") != null ? rs.getTimestamp("last_login").toLocalDateTime() : null);
        user.setIsActive(rs.getString("is_active"));
        return user;
    }
}
